package com.itheima.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Freeze;
import com.itheima.domain.mongo.Movement;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.FreezeService;
import com.itheima.service.mongo.MovementService;
import com.itheima.vo.CommentVo;
import com.itheima.vo.MovementVo;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class UserManager {

    @DubboReference
    UserInfoService userInfoService;

    @DubboReference
    MovementService movementService;

    @DubboReference
    CommentService commentService;

    public ResponseEntity findByPage(Integer pageNum, Integer pageSize) {
        PageBeanVo pageBeanVo = userInfoService.findByPage(pageNum, pageSize);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findUserInfoById(Long userId) {
        UserInfo userInfo = userInfoService.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    public ResponseEntity findMovementByCondition4Page(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        //1.判断uid是否为空,若不为空查询userInfo
        UserInfo userInfo = null;
        if (userId != null) {
            userInfo = userInfoService.findById(userId);
        }

        //2.远程调用service查询pageBeanvo
        PageBeanVo pageBeanVo = movementService.findMovementByCondition4Page(userId, state, pageNum, pageSize);

        //3.获取pageBeanVo中动态集合
        List<Movement> items = (List<Movement>) pageBeanVo.getItems();

        //4.遍历动态集合,获取每个动态,若uid为空是查询动态的发布人userInfo,将动态和userInfo封装成MovementVo对象,将vo放入声明好的voList中
        List<MovementVo> voList = new ArrayList<>();
        if (CollUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                //若uid为空是查询动态的发布人userInfo
                if (userId == null) {
                    userInfo = userInfoService.findById(movement.getUserId());
                }

                //将动态和userInfo封装成MovementVo对象
                MovementVo vo = new MovementVo();

                //先userInfo后movement
                vo.setUserInfo(userInfo);
                vo.setMovement(movement);

                //单独处理下日期
                vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));

                voList.add(vo);
            }
        }

        //5.将voList设置给pageBeanVo
        pageBeanVo.setItems(voList);
        //6.返回pageBeanVo即可
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findMovementById(String movementId) {
        //1.远程调用service查询动态详情
        Movement movement = movementService.findById(new ObjectId(movementId));

        //2.远程调用service查询动态发布人userInfo
        UserInfo userInfo = userInfoService.findById(movement.getUserId());

        //3.封装MovementVo对象且返回
        MovementVo vo = new MovementVo();
        //先userInfo后movement
        vo.setUserInfo(userInfo);
        vo.setMovement(movement);

        //单独处理下时间
        vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findMovementComemntByPage(String movementId, Integer pageNum, Integer pageSize) {
        //1.远程调用commentService查询pageBeanVo
        PageBeanVo pageBeanVo = commentService.findCommentByPage(new ObjectId(movementId), pageNum, pageSize);

        //2.获取pageBeanVo中评论list
        List<Comment> items = (List<Comment>) pageBeanVo.getItems();

        //3.遍历评论list,获取每个评论,获取评论人的userInfo,将评论和userInfo封装CommentVo对象,将每个vo放入声明好的voList中
        List<CommentVo> voList = new ArrayList<>();
        if (CollUtil.isNotEmpty(items)) {
            items.forEach(comment -> {
                //获取评论人的userInfo,
                UserInfo userInfo = userInfoService.findById(comment.getUserId());

                //将评论和userInfo封装CommentVo对象,
                CommentVo vo = new CommentVo();
                vo.setId(comment.getId().toString());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setContent(comment.getContent());
                vo.setCreateDate(DateUtil.formatDateTime(new Date(comment.getCreated())));

                //将每个vo放入声明好的voList中
                voList.add(vo);
            });
        }

        //4.将voList设置给pageBeanVo
        pageBeanVo.setItems(voList);
        //5.返回pageBeanVo
        return ResponseEntity.ok(pageBeanVo);
    }

    @DubboReference
    FreezeService freezeService;

    // 冻结用户
    public ResponseEntity saveFreeze(Freeze freeze) {

        //0. 获取userId
        Integer userId = freeze.getUserId();

        //0.1 根据userId查询用户是否存在被冻结信息
        Freeze freezeByUserId = freezeService.findById(userId);

        String message = "";
        if (freezeByUserId == null) {
            //1. 设置,id-冻结状态-冻结起始毫秒值
            freeze.setId(ObjectId.get());
            freeze.setUserStatus("2");
            freeze.setCreated(System.currentTimeMillis());
            //2. 调用service保存数据
            message = freezeService.saveFreeze(freeze);
            userInfoService.updateStatus(freeze.getUserId(), "2");
        } else {
            freezeByUserId.setCreated(System.currentTimeMillis());
            freezeByUserId.setFreezingRange(freeze.getFreezingRange());
            freezeByUserId.setFreezingTime(freeze.getFreezingTime());
            freezeByUserId.setFrozenRemarks(freeze.getFrozenRemarks());
            freezeByUserId.setReasonsForFreezing(freeze.getReasonsForFreezing());
            freezeByUserId.setUserStatus("1");
            // 10. 修改
            message = freezeService.saveFreeze(freezeByUserId);
            userInfoService.updateStatus(freeze.getUserId(), "2");
        }


        //3. 调用redis设置冻结状态及冻结天数
        freezeService.saveStatus(freeze);

        //4. 返回结果
        HashMap<String, String> map = new HashMap<>();
        map.put("message", message);

        return ResponseEntity.ok(map);
    }

    // 解冻用户
    public ResponseEntity unfreeze(Map<String, String> param) {

        //1. 获取参数
        Integer userId = Integer.parseInt(param.get("userId"));
        String reasonsForThawing = param.get("reasonsForThawing");   // 解冻原因

        //2. 用userId查询冻结信息
        Freeze freeze = freezeService.findById(userId);

        //3. 判断冻结时间     3\7 不删redis数据,永久的调用service删除数据
        //3.1 声明map集合,封装返回结果
        HashMap<String, String> map = new HashMap<>();
        switch (freeze.getFreezingTime()) {
            case 1:
                map.put("message", "冻结三天,自动解冻");
                return ResponseEntity.status(500).body(map);
            case 2:
                map.put("message", "冻结7天,自动解冻");
                return ResponseEntity.status(500).body(map);
        }
        map.put("message","不在三界之中,处于五行之外");
        return ResponseEntity.ok(map);
    }


    //复审--通过
    public ResponseEntity reviewMovement(String[] pushIdlist) {

        //遍历集合
        for (String pushId : pushIdlist) {
            Movement movement = movementService.findById(new ObjectId(pushId));
            movement.setState(1); //改变参数
            movementService.updateState(movement);
        }
        //返回map
        HashMap<String, String> map = new HashMap<>();
        map.put("message","审核完成--已通过");
        return ResponseEntity.ok(map);
    }

    //复审--拒绝
    public ResponseEntity rejectMovement(String[] pushIdList) {
        //遍历动态id集合
        for (String pushId : pushIdList) {
            Movement movement = movementService.findById(new ObjectId(pushId));
            movement.setState(2);  //修改状态参数  "2"拒绝
            movementService.updateState(movement);
        }
        //返回结果
        HashMap<String, String> map = new HashMap<>();
        map.put("message","审核完成--已拒绝");
        return ResponseEntity.ok(map);
    }


}